home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / ptv1n1.arc / L5.C < prev    next >
Text File  |  1990-06-08  |  2KB  |  62 lines

  1. /*
  2.  * *** Listing 5 ***
  3.  *
  4.  * Program to calculate the 16-bit checksum of the stream of bytes
  5.  * from the specified file.  Buffers the bytes internally, rather
  6.  * than letting C or DOS do the work.
  7.  */
  8. #include <stdio.h>
  9. #include <fcntl.h>
  10. #include <alloc.h>   /* alloc.h for Turbo C 2.0,
  11.                         malloc.h for Microsoft C 5.0 */
  12.  
  13. #define BUFFER_SIZE  0x8000   /* 32Kb data buffer */
  14.  
  15. main(int argc, char *argv[]) {
  16.    int Handle;
  17.    unsigned int Checksum;
  18.    unsigned char *WorkingBuffer, *WorkingPtr;
  19.    int WorkingLength, LengthCount;
  20.  
  21.    if ( argc != 2 ) {
  22.       printf("usage: checksum filename\n");
  23.       exit(1);
  24.    }
  25.  
  26.    if ( (Handle = open(argv[1], O_RDONLY | O_BINARY)) == -1 ) {
  27.       printf("Can't open file: %s\n", argv[1]);
  28.       exit(1);
  29.    }
  30.  
  31.    /* Get memory in which to buffer the data */
  32.    if ( (WorkingBuffer = malloc(BUFFER_SIZE)) == NULL ) {
  33.       printf("Can't get enough memory\n");
  34.       exit(1);
  35.    }
  36.  
  37.    /* Initialize the checksum accumulator */
  38.    Checksum = 0;
  39.  
  40.    /* Process the file in BUFFER_SIZE chunks */
  41.    do {
  42.       if ( (WorkingLength = read(Handle, WorkingBuffer,
  43.             BUFFER_SIZE)) == -1 ) {
  44.          printf("Error reading file %s\n", argv[1]);
  45.          exit(1);
  46.       }
  47.       /* Checksum this chunk */
  48.       WorkingPtr = WorkingBuffer;
  49.       LengthCount = WorkingLength;
  50.       while ( LengthCount-- ) {
  51.          /* Add each byte in turn into the checksum accumulator */
  52.          Checksum += (unsigned int) *WorkingPtr++;
  53.       }
  54.    } while ( WorkingLength );
  55.  
  56.    /* Report the result */
  57.    printf("The checksum is: %u\n", Checksum);
  58.  
  59.    exit(0);
  60. }
  61.  
  62.